<template>
    <div class="confirm-modal-box medical-waste">
        <div class="condition-filter-box">
            <button :class="['button',todayActive ? 'btn-active' : '']" @click="checkToday('clear')">今日</button>
            <el-date-picker
                v-model="time"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
            />
        </div>
        <div>
            <div class="filter-btn-item left-item">
                <button
                    v-for="item in dataList"
                    :key="item.id"
                    :class="['button',item.isActive ? 'btn-active' : '']"
                    @click="changeTypeActive(item)">
                    {{item.name}}
                </button>
            </div>
            <div class="filter-btn-item right-item">
                <span>网页交接</span>
            </div>
        </div>

        <div style="padding: 0 5px;">
            <div class="left-btn">
                <el-input v-model="text" type="number" placeholder="请输入单号" clearable/>
                <button class="button" @click="searchOrder">查单号</button>
                <button :class="['button',isFilterStatus == 0 ? 'btn-active' : '']" @click="changeFilter(0)">全部</button>
                <button :class="['button',isFilterStatus == 1 ? 'btn-active' : '']" @click="changeFilter(1)">已交接</button>
                <button :class="['button',isFilterStatus == 2 ? 'btn-active' : '']" @click="changeFilter(2)">待交接</button> <!-- 原:仅显示未确认-->
                <ExportBtn :isDetailModal="true"  v-if="exportLimit != '1' && this.pageTotal > 0" :name="'导出搜索结果'" :checkType="checkType" :currOrders="currOrders" :fileName="`医废数据 ${date.st}_${date.et}`" />
                <el-button v-else class="primary-btn" type="primary" @click="showTips" :disabled="isExporting">导出搜索结果</el-button>
                <QualityBox v-if="hasControl" :content="`${resultTips}`" :dateTips="`${date.st} - ${date.et}`" text="say快捷下单详细查询"></QualityBox>
            </div>
            <div class="right-btn">
                <div class="select-btn-list">
                    <button class="button" @click="toggleSelect(orderInfo, 0)">全选</button>
                    <button class="button" @click="toggleSelect(orderInfo, 1)">反选</button>
                    <button class="button" @click="toggleSelect()">取消</button>
                    <button class="button" @click="showFill()">确认</button>
                </div>
            </div>
        </div>

        <transition name="fade">
            <div class="result-tips" v-if="isShowResultTips">
                <h3>
                    <span>{{resultTips}}</span>
                    <span class="hide-btn" @click="hideResultTips">暂不显示</span>
                </h3>
            </div>
        </transition>

        <div class="sign-pic-modal" v-if="isShowSign" @click="isShowSign = false;">
            <div class="sign-pic-content">
                <img :src="currSignPic" alt="">
            </div>
        </div>

        <!-- 表格 -->
        <el-table
            ref="multipleTable"
            size="mini"
            :data="orderInfo"
            height="550"
            border
            style="width: 100%"
            v-loading="isLoading"
            element-loading-text="拼命加载中..."
            element-loading-background="rgba(255, 255, 255, 0.5)"
            @selection-change="handleSelectionChange">
            <el-table-column
                type="selection"
                align="center"
                width="55">
            </el-table-column>
            <el-table-column
                v-for="(item,index) in tableCol"
                :key="index"
                align="center"
                :label="item.label"
                :prop="item.prop"
                :width="item.width">
                <template slot-scope="scope">
                    <span v-if="item.label == '类型'" class="type-name" :style="{background:scope.row.colour}">{{scope.row.namewc}}</span>
                    <span v-else-if="item.type != 'selection'">{{scope.row[item.prop]}}{{item.label == '重量' ? 'kg' : ''}}</span>
                </template>
                <div v-if="item.label == '科室交接'">
                    <el-table-column
                        v-for="(val, idx) in getSub(item.sub)"
                        :key="idx"
                        align="center"
                        :label="val.label"
                        :prop="val.prop"
                        :width="val.width">
                        <template slot-scope="scope">
                            <div v-if="item.label == '科室交接' && val.label == '交接时间'">
                                <span v-if="currHosiptalId == 21 || currHosiptalId == 22">{{scope.row.step == '0' ? '' : '已确认'}}</span>
                                <span v-else>{{scope.row.step1_time}}</span>
                            </div>
                            <div v-else-if="item.label == '科室交接' && val.label == '交接确认'">
                                <!-- <template v-if="$root.$data.is_szy">
                                    <span >{{scope.row.step1_uinfo}}</span> -->
                                    <!-- <span v-if="scope.row.step1_uinfo != '' && scope.row.step1_uname != ''">，</span>
                                    <span>{{scope.row.step1_method == 'APP确认' ? '现场签名确认':scope.row.step1_uname}}</span> -->
                                <!-- </template> -->
                                <!-- <template> -->
                                    <span >{{scope.row.step1_uinfo ? scope.row.step1_uinfo : scope.row.step1_uname}}</span>
                                    <!--v-if="currHosiptalId == 21 || currHosiptalId == 22" <span v-else>{{scope.row.step1_method == 'APP确认' ? '现场签名确认':scope.row.step1_uname}}</span> -->
                                <!-- </template> -->
                                
                                <div v-if="scope.row.step1_sign != ''">
                                    <img :src="scope.row.step1_sign" alt="" @click="showSign(scope.$index, scope.row, scope.row.step1_sign)" style="width: 25px;vertical-align: middle;">
                                </div>
                            </div>
                            <div v-else>
                                <span>{{scope.row[val.prop]}}</span>
                            </div>
                        </template>
                    </el-table-column>
                </div>
            </el-table-column>
        </el-table>
        <div class="paginate-wrapper">
          <Pagination v-if="pageTotal > 0" :total="pageTotal" :pageSize="pageSize" @handleCurrentChange="handleChangeNumber"></Pagination>
        </div>

        <el-dialog
            :title="'请填写'+($root.$data.is_szy ? '工号':'全名')+'(必填)'"
            :visible.sync="isShowFill"
            :modal-append-to-body="false"
            width="440px"
            @close="toggleSecondConfirm(2)">
            <input type="text" v-model="required" @change="handleGetName">
            <div class="szy-confirm-info" v-if="$root.$data.is_szy">
                <span class="gary">工号姓名：</span>
                <span class="gary" v-if="!szy_required">暂无数据；请输入工号，回车键（enter）获取信息</span>
                <span v-else>{{szy_required}}</span>
            </div>
            <div class="btn-box">
                <button @click="toggleSecondConfirm()">确定</button>
            </div>
        </el-dialog>

        <el-dialog
            width="30%"
            title=""
            top="30px"
            :visible.sync="innerVisible"
            :modal="false"
            class="confirm-pop">
            <div slot="title">
                <span class="el-icon-warning"></span> 是否确认
            </div>
            <div class="handle-box">
                <el-button type="info" @click="toggleSecondConfirm(1)">取消</el-button>
                <el-button type="primary" @click="sendConfirm">确认</el-button>
            </div>
        </el-dialog>

        <div class="v-mask" v-if="canShowTips" @click="hideTips"></div>
        <ExportWarmTips 
          v-if="canShowTips"
          :data="undoTableData" 
          :day="getDateText"
          @handle-jump="switchDayLis"
          @handle-close="hideTips">
          <div class="export-btn">
              <ExportBtn 
                :name="'立即导出'" 
                :curr-orders="currOrders" 
                :file-name="`医废数据 ${date.st}_${date.et}`" 
                :is-detail-modal="true" 
                :check-type="checkType" 
                @handleCancel="hideTips" 
              />
          </div>
        </ExportWarmTips>

        <BatchHandover
          :show="canShowDayLis"
          :data="undoTableData"
          :col="colL"
          :day-lis="dayLis"
          :date="showDate"
          :export-day="getDateText"
          @handle-show-lis="switchDayLis"
          @handle-show-sign="switchSignModal"
          @handle-show-confirm="handleShowConfirm"
          @handle-show-classify-order="handleShowClassifyOrder"
        ></BatchHandover>

        <SignModal
            v-if="signVisible"
            :signType="'multiple'"
            :orders="undoTableData"
            @sure="handleSureSuccess"
            @handleCancel="switchSignModal"
        />

        <el-dialog
            :title="orderLis.title"
            :visible.sync="orderShow"
            :modal-append-to-body="false"
            width="90%">
            <WasteLis
                :order="orderLis"
            ></WasteLis>
        </el-dialog>

        <el-dialog
            title="医废确认"
            :visible.sync="confirmShow"
            :modal-append-to-body="false"
            width="740px">
            <HandConfirm
                v-if="confirmShow"
                :order="confirmOrder"
                :show-time="showDate"
                @sure="handleSureSuccess"
                @show-order="handleShowClassifyOrder"
            ></HandConfirm>
        </el-dialog>
    </div>
</template>

<script>
    import {
        wasteDetailsUrl, wastecategoryUrl, wasteConfirmUrl,
        getHconfLisUrl, getDepartmentMyInfoUrl,wasteFindNameUrl
    } from '../../common/ajax';
    import WasteLis from './sub/WasteLis';
    import HandConfirm from './sub/HandConfirm';
    import Pagination from '../pagination';
    import QualityBox from './quality-btn';
    import ExportBtn from './export-btn';
    import SignModal from './sign-modal';
    import ExportWarmTips from './export-warm-tips';
    import BatchHandover from './batch-handover';
    import cookie from '../../common/cookie';
    import {mapActions} from "vuex"
    import store from '../../store';
    export default {
        data(){
            return{
                pickerOptions: {   // 禁选当天之后的日期
                    disabledDate(date) {
                        return date.getTime() > Date.now();
                    }
                },
                dataList: [
                    // { id: 1, name: '感染性', color: '#F44336', isActive: true }, // 不能用red blue等，color-picker无法识别
                ],
                orderInfo: [
                    // {
                    //     cid: '17',
                    //     colour: "#ffd336",
                    //     namewc: '感染性',
                    //     place: '1号楼26楼B区内二科',
                    //     ks: '内二科',
                    //     ctime: '2018/9/13 11:32',
                    //     weight: '1.9',
                    //     uname: '乔大大',
                    //     sn: '1536809540000',
                    //     status: '已确认',
                    //     step1_method: '平台确认',
                    //     step1_time: '2018/9/13 22:00',
                    //     step1_uinfo: 'gyt',
                    //     step2_method: '微信确认',
                    //     step2_time: '2018/9/14 12:00',
                    //     step2_uname: 'kwan'
                    // }
                ],
                currShowOrder: [],
                text: '',
                // 时刻选择
                pickTime: [
                    new Date().getTime() - 1000 * 60 * 60 * 2,
                    new Date().getTime() - 1000 * 60 * 60
                ],
                shm:'',
                ehm:'',
                // 日期选择
                date:{
                    st:'',
                    et:''
                },
                time:'',
                tmpNum: '',
                roomList: [
                    // {
                    //     id: 1,
                    //     name: 'xxx'
                    // }
                ],
                currSelect: '',
                tipsText: '添加科室过滤',
                noDataText: '还没有添加任何科室哦',
                checkType: [],   // 存放指定要查看的医废类型
                todayActive: false,
                msgText: '',
                msgFlag: false,
                multipleSelection: [],   // 需要提交确认的数组
                isFilterStatus: 0,
                isShowSign: false,
                isShowFill: false,   // 是否显示modal，填写姓名或工号
                isSubmiting: false,
                innerVisible: false,
                tagNum: 0,
                currHosiptalId: Cookies.get('categoryid'),
                required: '',
                szy_required:"",
                currSignPic: '',
                currOrders: [],  // 待导出数组orders
                isShowResultTips: false,
                tableCol: [
                    { label: '类型', prop: 'namewc', width: '100' },
                    { label: '楼栋', prop: 'ld', width: '150' },
                    { label: '楼层', prop: 'lc', width: '150' },
                    { label: '科室', prop: 'ks', width: '150' },
                    { label: '收集时间', prop: 'ctime', width: '120' },
                    { label: '重量', prop: 'weight', width: '90' },
                    { label: '数量', prop: 'num', width: '' },
                    { label: '收运称重人', prop: 'uname', width: '120' },
                    { label: '条形码', prop: 'sn', width: '145' },
                    { label: '状态', prop: 'status', width: '' },
                    
                ],
                isLoading: false,
                canShowTips: false,
                canShowDayLis: false,
                dayLis: {
                    data: [],
                    types: [
                        // { namewc: '感染性', totals: '100' }
                    ]
                },
                undoTableData: [],
                signVisible: false,
                isExporting: false,
                exportLimit: '',
                showDate:{day:'',time:''},
                colL:[
                    {title:'时间',width:''},
                    {title:'类型',width:''},
                    {title:'数量',width:''},
                    {title:'重量',width:''},
                    {title:'收运称重人',width:''},
                    {title:'状态',width:''}
                ],
                orderLis:{},
                orderShow:false,
                confirmOrder:{},
                confirmShow:false,
                pageIndex: 1,
                pageSize: 100,
                pageTotal: 0,
                resultTips: '',
                hasControl: '',
            }
        },
        created(){
            let hw_show_signtime = Cookies.get("hw_show_signtime")
            if(hw_show_signtime && hw_show_signtime == '1'){
                this.tableCol.push({
                    label: '科室交接',
                    prop: '',
                    width: '',
                    sub: [
                        { label: '交接确认', prop: 'step1_uinfo', width: '120' },
                        { label: '交接方式', prop: 'step1_method', width: '75' },
                    ]
                })
            }else {
                this.tableCol.push({
                    label: '科室交接',
                    prop: '',
                    width: '',
                    sub: [
                        { label: '交接确认', prop: 'step1_uinfo', width: '120' },
                        { label: '交接方式', prop: 'step1_method', width: '75' },
                        { label: '交接时间', prop: 'step1_time', width: '120' },
                    ]
                })
            }
            this.getWasteUserKs()
            this.checkExportLimit();
            this.checkToday()
            this.getTypeData()
        },
        components:{
            ExportBtn,
            SignModal,
            WasteLis,
            HandConfirm,
            Pagination,
            QualityBox,
            ExportWarmTips,
            BatchHandover,
        },
        watch:{
            'time'(){
                if(this.time == null) {
                    this.checkToday()
                    this.stDisable = true;
                    this.startTime = '';
                    this.postAllData()   // 减少一次请求，checkToday()里已发送请求
                    return;
                }else{
                    this.stDisable = false;
                    this.getTime()
                    this.postAllData()
                }

                if(this.todayActive) this.todayActive = false
            }
        },
        computed: {
          getDateText(){
            return `${this.date.st}${`${this.date.st != this.date.et ? ` 至 ${this.date.et}` : ''}`}`
          },
          getSub(){
            return function(item){
              return ['63','64'].includes(cookie.get('categoryid')) ? item.filter(v => v.label !== '交接时间') : item
            }
          },
          hasBindKs(){
            if(store.state.hwUserKs && store.state.hwUserKs.length > 0){
                return true
            }
            return false
          }
        },
        methods:{
            handleChangeNumber(val){
              this.pageIndex = val;
              this.postAllData()
            },
            handleSureSuccess(type,order){
                //二次确认成功后的操作
                this.confirmShow = false;
                this.postAllData()
                // if(type == 1){
                //     this.handleGetLis(0, order)
                // }else {
                //     this.handleGetLis(1, order);
                // }
            },
            //点击显示同类型的单
            handleShowClassifyOrder(order){
                if(order.lis.length == 0) return;  // 数量为0时不可点击查看
                this.orderLis = order;
                this.orderShow = true
            },
            //点击待交接
            handleShowConfirm(val){ //显示确认
                // if(val.title == '已交接' || val.staff.length == 0) return;
                this.confirmOrder = val;
                this.confirmShow = true;
                // this.isShowFill = true;
            },
            checkExportLimit(){
                jQuery.ajax({
                    url: getHconfLisUrl,
                    type: 'GET',
                    success: function(data){
                        if(data.success){
                            this.exportLimit = data.data.hw_export_limit
                            this.hasControl = data.data.hw_quality_control
                        }
                    }.bind(this),
                    error: function(err){
                        throwErrorTips('暂无数据',err.msg)
                    }
                })
            },
            switchSignModal(){
                this.signVisible = !this.signVisible;
            },
            switchDayLis(){
                this.hideTips();
                this.canShowDayLis = !this.canShowDayLis
            },
            hideTips(isExporting){
//                if(typeof(isExporting) == 'boolean') this.isExporting = isExporting;
                this.canShowTips = false;
            },
            showTips(){    //
                if(this.orderInfo.length == 0) {
                    throwErrorTips('暂无数据','')
                    return;
                }
                this.canShowTips = true;
            },
            getDayLis(data){
                this.dayLis = {
                    data: [],
                    types: []
                },
                this.dayLis.data = data.filter(v => v.step == 0)
                let arr = Array.from(new Set(data.map(v => v.namewc)))
                arr.forEach(v => {
                    let obj = {
                        namewc: v,
                        totals: 0
                    }
                    obj.totals = this.dayLis.data.filter(v2 => v2.namewc == v).length
                    this.dayLis.types.push(obj)
                })
            },
            hideResultTips(){
                this.isShowResultTips = false;
            },
            showSign(index, row, imgSrc){
                this.isShowSign = true;
                this.currSignPic = imgSrc;
            },
            showFill(){
                
                if(this.multipleSelection.length == 0) {
                    this.$Message({
                        showClose: true,
                        message: '请先勾选至少一张单',
                        type: 'error'
                    });
                    return;
                }
                this.isShowFill = true;
            },
            toggleSecondConfirm(num = 0){   // 1:点击取消
                if(num == 0){
                    if(this.required.trim() == '' || (this.$root.$data.is_szy && !this.szy_required)){
                        this.$Message({
                            showClose: true,
                            message: this.$root.$data.is_szy?'填写工号获取信息后才能提交':'工号或姓名不能为空',
                            type: 'error'
                        });
                    }else{
                        this.isShowFill = false;
                        this.innerVisible = true;
                    }
                }
                if(num == 1){
                    this.isShowFill = true;
                    this.innerVisible = false;
                }
                if(num == 2){
                    this.isShowFill = false;
                }
            },
            handleGetName(){
                if(!this.$root.$data.is_szy) return
                if(!this.required.trim()){
                    this.szy_required = ""
                    return
                }
                jQuery.ajax({
                    url: wasteFindNameUrl,
                    type: 'get',
                    data:{code:this.required.trim()},
                    success: function(res){
                        if(res.success && res.data && res.data != "0") {
                            this.szy_required = this.required.trim()+res.data
                        }else {
                            this.szy_required = ""
                        }
                    }.bind(this)
                })
            },
            sendConfirm(){
                if(!this.isSubmiting) {
                    this.innerVisible = false;
                    this.isShowFill = false;
                    this.isSubmiting = true;
                    let arr = this.multipleSelection.map(v => parseInt(v.id))
                    let obj = {
                        step1_uinfo: this.$root.$data.is_szy ? this.szy_required : this.required,
                        ids: arr
                    }
                    jQuery.ajax({
                        url: wasteConfirmUrl,
                        type: 'POST',
                        data: JSON.stringify(obj),
                        contentType: 'application/json;charset=UTF-8',
                        success: function(res){
                            if(res.success) {
                                this.postAllData()
                                this.$Message({
                                    showClose: true,
                                    message: '医废确认成功',
                                    type: 'success'
                                });
                            }else{
                                throwErrorTips('提交失败',res.msg)
                            }
                        }.bind(this)
                    })

                    setTimeout(()=>{
                        this.isSubmiting = false;
                    },200)
                }
            },
            handleSelectionChange(val){
                this.multipleSelection = val;
            },
            toggleSelect(rows, num){
                if(rows && num == 0){       // 全选
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleAllSelection(row)
                    })
                }else if(rows && num == 1){ // 反选
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row)
                    })
                }else{  // 取消
                    this.$refs.multipleTable.clearSelection()
                }
            },
            searchTime(){
                if(this.pickTime == null) {
                    this.shm = ''
                    this.ehm = ''
                }else{
                    this.shm = `${`00${new Date(this.pickTime[0]).getHours()}`.substr(-2)}:${`00${new Date(this.pickTime[0]).getMinutes()}`.substr(-2)}`
                    this.ehm = `${`00${new Date(this.pickTime[1]).getHours()}`.substr(-2)}:${`00${new Date(this.pickTime[1]).getMinutes()}`.substr(-2)}`
                }
                this.postAllData()
            },
            checkToday(text){
                if(text == 'clear') this.time = null

                let d = new Date()
                this.getTime(d)

                this.todayActive = true
            },
            changeTypeActive(item){
                item.isActive = !item.isActive

                let idx = this.checkType.findIndex(v => v == item.id)
                item.isActive ? this.checkType.push(item.id) : this.checkType.splice(idx, 1)

                this.postAllData()
            },
            getTypeData(){
                jQuery.ajax({
                    type: 'GET',
                    url: wastecategoryUrl,
                    success: function(res) {
                        if(res.success){
                            this.dataList = res.data
                            this.dataList = this.dataList.map(v => Object.assign({}, v, {isActive: true}))

                            this.checkType = this.dataList.map(v => v.id)

                            this.postAllData()
                        }else {
                            throwErrorTips('',res.msg)
                        }

                    }.bind(this)
                })
            },
            changeFilter(num){
                this.isFilterStatus = num
                this.postAllData()
            },
            handleAjax(form){
                
              return new Promise((resolve, reject) => {
                jQuery.ajax({
                  type: 'POST',
                  url: wasteDetailsUrl,
                  dataType: 'json',
                  contentType: 'application/json;charset=UTF-8',
                  data: JSON.stringify(form),
                  success: function(res){
                    if(res.success){
                      resolve(res);  // Promise中不使用return res
                    }else{
                      throwErrorTips('',res.msg)
                    }
                  }.bind(this)
                })
              })
            },
            postUndoData(){
                let filter_room = []
                this.roomList.forEach(v => {
                    filter_room.push(v.name)
                })

                let form = {
                    st: this.date.st == '' ? '2018-03-20' : this.date.st,
                    et: this.date.et == '' ? '2018-06-20' : this.date.et,
                    filter_ks: filter_room,
                    cs: this.checkType,
                    shm: this.shm,
                    ehm: this.ehm,
                    filter_my_ks: true, // true查当前绑定的所有科室的全部单，false查全部科室的全部单
                    filter_step_in: [0],  // 点击显示已交接时，如只要已交接1，则[1]，如没有点击，则[]
                    // filter_step: 1
                    page_index: this.pageIndex,
                    page_size: 9999,   // 用于获取指定范围所有未交接，将size设置9999
                    opt: 1
                }
                this.handleAjax(form).then(res => {
                  this.undoTableData = []
                  if(res.data.lis.length > 0) {
                      this.getDayLis(res.data.lis)
                      this.generateUndo(res.data.lis)
                  }
                })
            },
            postAllData(){
                if(!this.hasBindKs){
                    
                    return
                }
                let filter_room = []
                this.roomList.forEach(v => {
                    filter_room.push(v.name)
                })

                let form = {
                    st: this.date.st == '' ? '2018-03-20' : this.date.st,
                    et: this.date.et == '' ? '2018-06-20' : this.date.et,
                    filter_ks: filter_room,
                    cs: this.checkType,
                    shm: this.shm,
                    ehm: this.ehm,
                    filter_my_ks: true, // true查当前绑定的所有科室的全部单，false查全部科室的全部单
                    filter_step_in: this.isFilterStatus == 1 ? [1] : (this.isFilterStatus === 2 ? [0] : []),  // 点击显示已交接时，如只要已交接1，则[1]，如没有点击，则[]
                    // filter_step: 1
                    page_index: this.pageIndex,
                    page_size: this.isFilterStatus === 2 ? 9999 : this.pageSize,
                    opt: 1
                }

                // this.orderInfo = [];
                this.isLoading = true;
                this.handleAjax(form).then(res => {
                  this.currOrders = []
                  if(this.isFilterStatus == 2){   // 如点击待交接，过滤出待交接单
                      res.data.lis = res.data.lis.filter(v => v.step == 0)
                  }
                  this.orderInfo = res.data.lis;
                  this.pageTotal = res.data.total;
                  this.resultTips = res.data.result;
                  if(res.data.lis.length > 0) {
                      this.currOrders = res.data.arr;
                      this.getDayLis(res.data.lis)
                      this.postUndoData();
                      this.processData()
                      this.isShowResultTips = true;
                  }else{
                      this.isShowResultTips = false;
                  }
                  this.currShowOrder = this.orderInfo;
                  this.isLoading = false;
                  this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
                })
            },
            generateUndo(data){
                this.undoTableData = []
                // 生成所有日期
                let all_date = this.getAllDate()

                let types = []
                this.dataList.forEach(v => {
                    types.push({
                        color: v.colour,
                        title: v.name
                    })
                })

                // 多一层日期匹配判断
                for(let d of all_date){
                    // 筛选出符合当前日期的单
                    let tmpData = data.filter(v => v.ctime.split(' ')[0] == d)

                    // 生成所有科室
                    let all_ks = Array.from(new Set(tmpData.map(v => v.place)))

                    let amlis1 = {date:d,title:'点击交接',name:'待交接',time:'00:00-12:59',staff:[],typeL:[],ks:[],types:types},
                        pmlis1 = {date:d,title:'点击交接',name:'待交接',time:'13:00-23:59',staff:[],typeL:[],ks:[],types:types},
                        amtypeL = [], pmtypeL = [],
                        amks = [], pmks = [];

                    for(var typeo of types){
                        let o = typeo;
                        o['lis'] = [];
                        o['weight'] = 0;
                        o['num'] = 0;
                        o = JSON.stringify(o);
                        amtypeL.push(JSON.parse(o));
                        pmtypeL.push(JSON.parse(o));
                    }
                    for(var k of all_ks){
                        let o = {ks:k};
                        o['lis'] = [];
                        o['weight'] = 0;
                        o['num'] = 0;
                        amks.push(o);
                        pmks.push(o);
                    }
                    for(var od of tmpData){
                        if(od.step == 0){
                            if(od.ctime.split(' ')[1] >= '00:00' && od.ctime.split(' ')[1] <= '12:59:59'){
                                amlis1.staff.push(od.uname)
                                for(let ty of amtypeL){
                                    if(ty.title == od.namewc){
                                        ty.lis.push(od);
                                        ty.weight += Number(od.weight);
                                        ty.num += Number(od.num)
                                    }
                                }
                                let ind = all_ks.indexOf(od.place);
                                if(ind != -1){
                                    amks[ind].lis.push(od);
                                    amks[ind].weight += Number(od.weight);
                                    amks[ind].num += Number(od.num)
                                }
                            }else if(od.ctime.split(' ')[1] >= '13:00' && od.ctime.split(' ')[1] <= '23:59:59'){
                                pmlis1.staff.push(od.uname)
                                for(let ty of pmtypeL){
                                    if(ty.title == od.namewc){
                                        ty.lis.push(od);
                                        ty.weight += Number(od.weight);
                                        ty.num += Number(od.num)
                                    }
                                }
                                let ind = all_ks.indexOf(od.place);
                                if(ind != -1){
                                    pmks[ind].lis.push(od);
                                    pmks[ind].weight += Number(od.weight);
                                    pmks[ind].num += Number(od.num)
                                }
                            }
                        }
                    }
                    amlis1.staff = Array.from(new Set(amlis1.staff))
                    pmlis1.staff = Array.from(new Set(pmlis1.staff))
                    amlis1.ks = amks;
                    pmlis1.ks = pmks;
                    amtypeL.forEach((value,ind)=>{
                        if(value.lis.length > 0){
                            amlis1.typeL.push(value)
                        }
                    })
                    pmtypeL.forEach((value,ind)=>{
                        if(value.lis.length > 0){
                            pmlis1.typeL.push(value)
                        }
                    })
                    if(amlis1.typeL.length > 0){
                        this.undoTableData.push(amlis1)
                    }
                    if(pmlis1.typeL.length > 0){
                        this.undoTableData.push(pmlis1)
                    }
                }

                if(this.undoTableData.length == 0 && this.canShowDayLis){  // 判断当前是否有未交接数据，如没有，则直接弹窗，提示可以导出上次选的时间
                    this.canShowDayLis = false;
                    this.canShowTips = true;
                }

                
                console.log('getUndoLis...');
                console.log(this.undoTableData);
            },
            searchOrder(){
                let data = {
                    sn: this.text
                }
                if(this.text != ''){
                    jQuery.ajax({
                        type: 'POST',
                        url: wasteDetailsUrl,
                        data: JSON.stringify(data),
                        dataType: 'json',
                        success: function(res){
                            if(res.success){
                                this.orderInfo = res.data.lis
                                if(res.data.lis.length > 0) this.processData()
                                this.text = ''
                            }else {
                                throwErrorTips('',res.msg)
                            }

                        }.bind(this)
                    })
                }else{
                    this.postAllData()
                }
            },
            processData(){
                this.orderInfo.forEach(v => {
                    let status = '', step1_method, step2_method, step_status_tips = '';
                    switch(v.step){
                        case '0': status = '已称重'; break;
                        case '1': status = '已确认'; break;
                        case '2': status = '已出库'; break;
                        default: status = ''; break;
                    }
                    if(v.sign1_time && v.step == 0){
                        status = '已确认'
                    }
                    if(v.step !== '0'){
                      switch(v.step1_way){
                          case '0': step1_method = 'APP确认'; break;
                          case '1': step1_method = '微信确认'; break;
                          case '2': step1_method = '网页端确认'; break;
                          case '4': step1_method = '微信确认'; break;
                          default: step1_method = ''; break;
                      }
                    }
                    if(v.step === '2'){
                      switch(v.step2_way){
                          case '0': step2_method = 'APP确认'; break;
                          case '1': step2_method = '微信确认'; break;
                          case '2': step2_method = '网页端确认'; break;
                          case '4': step2_method = '微信确认'; break;
                          default: step2_method = ''; break;
                      }
                    }
                    Object.assign(v, {
                        status: status,
                        step1_method: step1_method,
                        step2_method: step2_method,
                    })
                })
            },
            getAllDate(){
                let arr = []
                let curr = new Date(this.date.st).getTime()
                let last = new Date(this.date.et).getTime()
                while(curr <= last){
                    arr.push(this.formatTime(new Date(curr)))
                    curr += 1000 * 60 * 60 * 24
                }
                return arr;
            },
            getTime(item){
                let st = {}, et = {}

                if(item != undefined){
                    st.year = et.year = item.getFullYear()
                    st.month = et.month = item.getMonth() + 1
                    st.day = et.day = item.getDate()
                }else{
                    st.year = this.time[0].getFullYear()
                    st.month = this.time[0].getMonth() + 1
                    st.day = this.time[0].getDate()
                    et.year = this.time[1].getFullYear()
                    et.month = this.time[1].getMonth() + 1
                    et.day = this.time[1].getDate()
                }

                if(st.month < 10) st.month = `0${st.month}`
                if(et.month < 10) et.month = `0${et.month}`
                if(st.day < 10) st.day = `0${st.day}`
                if(et.day < 10) et.day = `0${et.day}`

                this.date = {
                    st: `${st.year}-${st.month}-${st.day}`,
                    et: `${et.year}-${et.month}-${et.day}`
                }
            },
            getDate(flag){      // flag表示是否需要在小于10的数字前加0
                let obj = {},
                    d = new Date(),
                    time;

                obj.year = d.getFullYear()
                obj.month = d.getMonth()
                obj.date = d.getDate()
                obj.hour = d.getHours()
                obj.min = d.getMinutes()
                obj.second = d.getSeconds()

                for(let v in obj) obj[v] = obj[v].toString()

                if(flag){
                    obj.month  = obj.month < 10 ? `0${obj.month}` : obj.month
                    obj.date = obj.date < 10 ? `0${obj.date}` : obj.date
                    obj.hour = obj.hour < 10 ? `0${obj.hour}` : obj.hour
                    obj.min = obj.min < 10 ? `0${obj.min}` : obj.min
                    obj.second = obj.second < 10 ? `0${obj.second}` : obj.second
                    // for(let v in obj) obj[v] = parseInt(obj[v])
                    // time = `${obj.year}/${month}/${date} ${hour}:${min}:${second}`
                }

                time = `${obj.year}/${obj.month}/${obj.date} ${obj.hour}:${obj.min}:${obj.second}`

                return time;
            },
            formatTime(date){
                const year = date.getFullYear()
                const month = date.getMonth() + 1
                const day = date.getDate()
                const hour = date.getHours()
                const minute = date.getMinutes()
                const second = date.getSeconds()

                // return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
                return [year, month, day].map(this.formatNumber).join('-')
            },
            formatNumber(n) {
                n = n.toString()
                return n[1] ? n : '0' + n
            },
            ...mapActions(["getWasteUserKs"])
        }
    }
</script>
<style>
.el-table td, .el-table th.is-leaf {
    border-bottom: 1px solid #ebeef5;
    border: 1px solid #ebeef5;
}
</style>


